importClass(android.content.res.ColorStateList);
importClass(android.graphics.drawable.StateListDrawable);
importClass(android.graphics.drawable.PaintDrawable);
importClass(android.view.ScaleGestureDetector);
importClass(android.graphics.Color);
importClass(android.view.View);


var FunctionButton = (function() {
    //继承ui.Widget
    util.extend(FunctionButton, ui.Widget);

    function FunctionButton() {
        //调用父类构造函数
        ui.Widget.call(this);
        this.defineAttr("imageText", (view, attr, value, defineSetter) => {
            view.setText(value);
        });
        this.defineAttr("textColor", (view, attr, value, defineSetter) => {
            view.setTextColor(Color.parseColor(value));
        });
        //自定义属性onClick，定义被点击时执行的代码
        this.defineAttr("onClick", (view, name, defaultGetter) => {
            return this._onClick;
        }, (view, name, value, defaultSetter) => {
            this._onClick = value;
        });
    }
    FunctionButton.prototype.render = function() {
        return (
            <button textSize="16sp"  w="30" h="30" gravity="center" textStyle="bold" padding="5dp"/>
        );
    }
    FunctionButton.prototype.onViewCreated = function(view) {
        view.on("click", () => {
            if (this._onClick) {
                eval(this._onClick);
            }
        });
        setSelector(view, "#ffffffff", "#E8BDBDBD", 15);
    }
    ui.registerWidget("func-button", FunctionButton);
    return FunctionButton;
})();


window = floaty.rawWindow(
    <frame id="floating">
        <relative id="rl_main" padding="20dp">
                            
            <func-button
                 id="plus"
                 imageText="┼"
                 textColor="black"
                 onClick="onLoad()"
                 layout_alignParentTop="true"
                 layout_alignParentLeft="true"/>
            <func-button
                 id="refresh"
                 imageText="↺"
                 textColor="black"
                 onClick="onRefresh()"
                 layout_alignParentTop="true"
                 layout_toRightOf="plus"
                 />
            
            <func-button
                id="stop"
                imageText="⊘"
                textColor="black"
                onClick="onStop()"
                layout_alignParentTop="true"
                layout_toRightOf="refresh"
                />
            <text 
                id="title" 
                w="*" 
                h="20"
                layout_alignParentTop="true"
                layout_alignParentEnd="true"/>
           
            <progressbar id="progress" layout_centerInParent="true"/>
            
            <webview id="webView" layout_below="title"/>
            
            <func-button
            id="stop"
            imageText="✕"
            textColor="black"
            onClick="onDestroy()"
            layout_alignParentBottom="true"
            layout_alignParentEnd="true"
            />
            <func-button
                id="back"
                imageText="⇦"
                textColor="black"
                onClick="onBack()"
                layout_alignParentBottom="true"
                layout_toLeftOf="forward"
            />
            <func-button
            id="forward"
            imageText="⇨"
            textColor="black"
            onClick="onForward()"
            layout_alignParentBottom="true"
            layout_toLeftOf="stop"
            />
            
            
        </relative>
    </frame>
);

var webView = window.webView;
var progressBar = window.progress;
var title = window.title;
var initialW = device.width / 1.4;
var initialH = device.height / 3;
window.setSize(initialW, initialH);
window.setPosition(100, 100);
setInterval(()=>{}, 50);

/*缩放手势*/
//记录窗口大小
var realW = initialW;
var realH = initialH;

//限制大小
var maxW = device.width;
var miniW = device.width/1.8;

var scaleGestureListener = {
    onScale : function (detector) {
        var factor = detector.getScaleFactor();                
        if(realW*factor > miniW && realW*factor < maxW) {
            realW *= factor;
            realH *= factor;
            window.setSize(realW, realH);
        }
        return false;
    },
    onScaleBegin : function (detector) {
        return true;
    },
    onScaleEnd : function (detector) {
        isScale = false;
    }
}

var gestureDetector = new ScaleGestureDetector(context,
     new ScaleGestureDetector.OnScaleGestureListener(scaleGestureListener));

var id = null;

window.webView.setOnTouchListener(function(view, event){
    //两秒无操作隐藏按钮
    switch (event.getAction()) {
        case event.ACTION_DOWN:
            if(id != null) {
                var num = window.rl_main.getChildCount();                
                for(var i=0; i<num; i++) {                 
                    var child = window.rl_main.getChildAt(i);
                    if(child.getVisibility() == View.GONE)                                         
                        child.setVisibility(View.VISIBLE);
                }            
                clearTimeout(id);
                id = null;
            }
            break;        
        case event.ACTION_UP:          
            id = setTimeout(()=>{
                var num = window.rl_main.getChildCount();
                for(var i=0; i<num; i++) {
                    var child = window.rl_main.getChildAt(i);
                    if(child instanceof android.widget.Button)              
                        child.setVisibility(View.GONE);                 
                 }
            
            },2000);                 
    }
    //手势管理
    gestureDetector.onTouchEvent(event);
    return false;
});

/*设置窗口拖动*/ 
//记录按键被按下时的触摸坐标
var x = 0,
    y = 0;

//记录按键被按下时的悬浮窗位置
var windowX, windowY;

window.floating.setOnTouchListener(function(view, event) {
    
    switch (event.getAction()) {
        case event.ACTION_DOWN:
            x = event.getRawX();
            y = event.getRawY();
            windowX = window.getX();
            windowY = window.getY();
            return true;
        case event.ACTION_MOVE:
            //移动手指时调整悬浮窗位置
            window.setPosition(windowX + (event.getRawX() - x),
                windowY + (event.getRawY() - y));
            return true;
        case event.ACTION_UP:           
            return true;
    }
    return true;
});

ui.run(()=>{webView.loadUrl("https://m.baidu.com/");});

function onLoad() {
    let windowX = window.getX();
    let windowY = window.getY();
    window.setPosition(-1000 ,-1000);
    ui.run(()=>{
        rawInput(null, webView.getUrl(), url => {
            if(webView){
                webView.loadUrl(url);
            }
            window.setPosition(windowX, windowY);
        });
        
    });
}

function onRefresh() {
    ui.run(()=>{
        webView.reload();
    });   
}

function onStop() {
    ui.run(()=>{
        webView.stopLoading();
    });   
}

function onForward() {
    ui.run(()=>{
        if (webView.canGoForward()) { //点击返回按钮的时候判断有没有上一页
            webView.goForward(); // goBack()表示返回webView的上一页面
        }
    });
}
function onBack() {
    ui.run(()=>{
        if (webView.canGoBack()) { //点击返回按钮的时候判断有没有上一页
            webView.goBack(); // goBack()表示返回webView的上一页面
        }
    });
}
function onDestroy() {
    ui.run(()=>{      
        //释放资源
        webView.destroy();
        webView = null;
        exit();
    });
}

function setSelector(view, normalColor, pressedColor, radius) {
     var pressedDrawable = createDrawable(pressedColor, radius);
     var normalDrawable = createDrawable(normalColor, radius);
     var selector = createSelectorDrawable(normalDrawable, pressedDrawable);
     ui.run(()=>{
         view.setBackgroundDrawable(selector);    
     });
}

function createDrawable(mColor, radius) { //color #ffffff  
    var drawable = new PaintDrawable(Color.parseColor(mColor));
    drawable.setCornerRadius(dpToPx(radius));
    return drawable;

}

function createSelectorDrawable(normalDrawable, pressedDrawable) {

    var stateListDrawable = new StateListDrawable();
    stateListDrawable.addState([android.R.attr.state_pressed], pressedDrawable); // 按下显示
    stateListDrawable.addState([0], normalDrawable); // 抬起显示
    return stateListDrawable;

}

function dpToPx(dps) {
    return Math.round(context.getResources().getDisplayMetrics().density * dps);
}
